﻿using System;
using System.Collections.Generic;
using theeg.GraphWpf.Models;

namespace theeg.GraphWpf.Arrangement
{
    internal static class ArrangementMediator
    {
        public static Node FindRoot(IList<Node> nodes)
        {
            Node root = null;
            int deg = 0;
            foreach (Node node in nodes)
            {
                if (node.GenericMarker == 1)
                    continue;

                if (root == null)
                {
                    root = node;
                    deg = root.OutgoingEdges.Count - root.IncomingEdges.Count;
                    continue;
                }

                if (root.IncomingEdges.Count != 0 &&
                    node.IncomingEdges.Count == 0 &&
                    node.OutgoingEdges.Count != 0)
                {
                    root = node;
                    deg = root.OutgoingEdges.Count - root.IncomingEdges.Count;
                    continue;
                }

                if (root.IncomingEdges.Count == 0 && node.IncomingEdges.Count != 0)
                    continue;

                int d = node.OutgoingEdges.Count - node.IncomingEdges.Count;
                if (d > deg)
                {
                    root = node;
                    deg = d;
                }
            }
            return root;
        }

        public static int Traverse(INode node, int x, int y, double gridSize1, double gridSize2, ref int depth)
        {
            if (node.GenericMarker != 0)
            {
                return -1;
            }

            depth = Math.Max(depth, y);

            node.GenericMarker = 1;

            int xTmp = x;
            int count = 0;
            int avgX = 0;
            for (int i = 0; i < node.OutgoingEdges.Count; i++)
            {
                Transition edge = node.OutgoingEdges[i];
                if (edge.Target == edge.Source) continue;
                int tmp = Traverse(edge.Target, x, y + 1, gridSize1, gridSize2, ref depth);
                if (tmp == -1) continue;
                avgX += (int)(edge.Target.Left);
                x = tmp;
                count++;
            }

            if (count != 0)
            {
                xTmp = avgX / count;
            }
            else
            {
                xTmp *= (int)gridSize1;
            }

            node.Left = xTmp;
            node.Top = gridSize2 * y;

            if (count == 0)
                return x + 1;
            return x;
        }
    }
}
